
local PlayScene = class("PlayScene", cc.load("mvc").ViewBase)

require "app.models.CollideManager"
require "app.models.Common"

local Snake = require "app.models.Snake"
local Fence = require "app.models.Fence"
local Block = require "app.models.Block"

local AppleFactory = require "app.models.AppleFactory"
local PortalFactory = require "app.models.PortalFactory"
local BlockFactory = require "app.models.BlockFactory"

local cTaskOfLevel = { 1, 2, 3 }

function PlayScene:StepNextLevel( )
    self.curLevel = self.curLevel + 1
    if self.curLevel > 3 then
        --回到第1关
        self.curLevel = 1
    end
    --重置游戏
    self:Reset()
end

local cMoveSpeed = 0.3

function PlayScene:onCreate()
    print("PlayScene:onCreate")
    -- add background image    
    display.newSprite("PlaySceneBg.jpg")
        :move(display.center)
        :addTo(self)

    self.curLevel = 1
    --绘制围墙
    self.fence = Fence.new(cBound, self)
    self:CreateScoreBoard()
    self:Reset()


    --触屏输入处理
    self:ProcessInput()   

    local tick = function( )
        if "running" == self.stage then
            self.snake:Update()

            local headX, headY = self.snake:GetHeadGrid()

            local event = CheckCollide(headX, headY)
            if nil ~= event and event.Name ~= "body1" then
                if event.Name == "apple" then 
                    self.appleFactory:Generate()

                    self.snake:Grow()
                    --LUA里没i++
                    self.score = self.score + 1
                    self:SetScore(self.score)
                    if self.score >= cTaskOfLevel[self.curLevel] then
                        --吃够这关要求的苹果数，跳到下一关
                        self:StepNextLevel()
                    end

                --注意LUA里是elseif，中间没空格！
                elseif event.Type == "portal" then
                    print(string.format("x = %s, y = %s", event.link.x, event.link.y))                    
                    self.snake:SetHeadGrid(event.link.x, event.link.y)
                elseif "fence" == event.Type or "body" == event.Type or "block" == event.Type then
                    self.stage = "dead"
                    self.snake:Blink(function( )
                        print("重置游戏")
                        self:Reset()
                    end)                
                end
            end
        end        
    end
    --第一个参数是你要注册的回调函数，第二个是执行该函数循环的秒数，第三个参数是是否暂停。
    cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, cMoveSpeed, false)
end

local function vector2Dir( x, y )
    if math.abs(x) > math.abs(y) then 
        if x < 0 then
            return "left"
        else
            return "right"
        end
    else
        if y < 0 then   --COCOS里是(0,0)在屏幕中心，Y轴小于0是往上，X轴往右走是大于0
            return "up"
        else
            return "down"
        end
    end
end 

function PlayScene:ProcessInput()
    --Touch处理的回调函数
    local function onTouchBegan(touch, event)
        --点击的位置
        local location = touch:getLocation()

        local visibleSize = cc.Director:getInstance():getVisibleSize()
        local origin = cc.Director:getInstance():getVisibleOrigin()

        local finalX = location.x - (origin.x + visibleSize.width / 2)
        local finalY = location.y - (origin.y + visibleSize.height / 2)

        local dir = vector2Dir(finalX, finalY)
        --设置蛇走的方向
        self.snake:SetDir(dir)
    end
  
    local listener = cc.EventListenerTouchOneByOne:create()
    --监听器注册回调函数
    listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN)
    local eventDispatcher = self:getEventDispatcher()
    --为事件源添加监听器
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self)
end

function PlayScene:Reset( )
    if nil ~= self.snake then
        self.snake:Kill()
    end
    if nil ~= self.appleFactory then
        self.appleFactory:Reset()
    end
    if nil ~= self.fence then
        self.fence:Reset()
    end
    if nil ~= self.portalFactory then
        self.portalFactory:Reset()
    end
    if nil ~= self.blockFactory then
        self.blockFactory:Reset()
    end
    
    --碰撞产生器对象
    self.blockFactory = BlockFactory.new(self)
    self:Load() 
    --创建苹果生成器对象
    self.appleFactory = AppleFactory.new(cBound, self) 
    --创建围墙对象
    self.fence = Fence.new(cBound, self)
    --传送门对象
    self.portalFactory = PortalFactory.new(cBound, self)
    --创建蛇对象
    self.snake = Snake.new(self)     

    --默认游戏状态
    self.stage = "running"

    --游戏默认分数
    self.score = 0
    self.SetScore(self, self.score) --等价于self:SetScore(self.score)
end

--显示分数
function PlayScene:CreateScoreBoard( )
    display.newSprite("score.png")
    :move(display.right - 200, display.cy + 150)
    :addTo(self)

    local ttfConfig = {}
    ttfConfig.fontFilePath = "Transformers.ttf"
    ttfConfig.fontSize = 22

    local score = cc.Label:createWithTTF(ttfConfig, "0")
    self:addChild(score)
    score:setPosition(display.right - 200, display.cy + 110)
    self.scoreLabel = score
end

function PlayScene:SetScore(score)
    self.scoreLabel:setString(string.format("%d", score))
end

function PlayScene:Load()
    local file = assert(dofile(string.format("scene%d.lua", self.curLevel)))
    self.blockFactory:Reset()

    for _, t in ipairs(file) do
        self.blockFactory:Add(t.x, t.y, t.index)
    end
    print("load ok")
end

return PlayScene
